package com.eslserver.dao;

import java.sql.SQLException;
import java.util.Collection;

import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.to.Image;
import com.eslserver.util.HibernateUtil;

public class DBImageDAO implements ImageDAO {
	public static final Logger LOG = LoggerFactory.getLogger(DBGroupDAO.class);

	protected DBImageDAO() throws SQLException {
		// Empty protected constructor to avoid unnecessary initialization
	}

	@Override
	public Image addImage(Image eslImage) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.save(eslImage);
		return eslImage;
	}

	@Override
	public void updateImage(Image eslImage) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.update(eslImage);
	}

	@Override
	public Image loadImageByImageID(Integer imageID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Image image = (Image) session.load(Image.class, imageID);
		return image;
	}

	@Override
	public void deleteImage(Integer imageID) {
		Image eslImage = loadImageByImageID(imageID);
		if (eslImage != null) {
			eslImage.setDelete(true);
			updateImage(eslImage);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Image> loadAllImages() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();

		Image image = Image.createImage();
		image.setDelete(false);

		Example example = Example.create(image);

		Collection<Image> imageCollection = session.createCriteria(Image.class)
				.add(example).list();

		return imageCollection;
	}

}
